package com.kui.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.kui.config.CosClientConfig;
import com.kui.exception.BusinessException;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import com.kui.manager.CosManager;
import com.kui.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Slf4j
public abstract class FileUploadTemplate {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;

    /**
     * 图片上传
     *
     * @param inputSource      文件
     * @param uploadPathPrefix 上传路径
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(inputSource);
        // 2.图片上传地址
        // 防止重复设置uuid
        String uuid = RandomUtil.randomString(16);
        // 拿到原文件命
        String originalFilename = getOriginalFilename(inputSource);
        // 拼接上传文件名
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        // 拼接上传路径
        String uploadFilePath = String.format("%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadFilePath, null);
            // 将文件保存到临时文件中
            // 处理文件来源（图片或者url）
            processFile(inputSource, file);
            // 获取到图片信息
            PutObjectResult putObjectResult = cosManager.puPictureObject(uploadFilePath, file);
            // 返回可访问地址
            return getUploadPictureResult(putObjectResult, uploadFilePath, originalFilename, file);
        } catch (Exception e) {
            log.error("file upload error, filePath = ", uploadFilePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            deleteTempFile(file, uploadFilePath);
        }
    }

    /**
     * 封装返回结果
     *
     * @param putObjectResult
     * @param uploadFilePath
     * @param originalFilename
     * @param file
     * @return
     */
    private UploadPictureResult getUploadPictureResult(PutObjectResult putObjectResult, String uploadFilePath, String originalFilename, File file) {
        ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
        // 封装返回结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
        uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        return uploadPictureResult;
    }

    protected abstract void processFile(Object inputSource, File file) throws Exception;

    protected abstract String getOriginalFilename(Object inputSource);

    protected abstract void validPicture(Object inputSource);


    /**
     * 删除临时文件
     *
     * @param file
     * @param filePath
     */
    private static void deleteTempFile(File file, String filePath) {
        if (file != null) {
            boolean deleteResult = file.delete();
            if (!deleteResult) {
                log.error("file delete error, filePath= {}", filePath);
            }
        }
    }
}
